
#include <BStyle>
#include <BPainter>
#include <BRender>
#include <BViewer>
#include <BCone>
#include <BCube>
#include <BImage>
#include <BMaterial>
#include <BReadWrite>
#include <BScene>
#include <BCylinder>
#include <BCapsule>

#include "GearHandler.h"

GearHandler::GearHandler()
{
	_nodeA = new BBody("nodeA");
	{
		BCylinder* cylinder = new BCylinder(4, 2, 64);
		_nodeA->insertShape(cylinder);
		_nodeA->setMass(1);
	}

	_hingeA = new BHingeRestraint();
	_hingeA->setBodyA(_nodeA);
	_hingeA->setAxisA(0, 0, 1);
	_hingeA->setAxisB(0, 0, 1);
	_hingeA->setPivotB(0, 0, 4);

	_nodeB = new BBody("nodeB");
	{
		BCapsule* capsule = new BCapsule(1, 2, 24);
		_nodeB->insertShape(capsule);
		_nodeB->setMass(1);
	}

	_hingeB = new BHingeRestraint();
	_hingeB->setBodyA(_nodeB);
	_hingeB->setAxisA(0, 0, 1);
	_hingeB->setAxisB(0, 0, 1);
	_hingeB->setPivotB(5, 0, 4);

	_restraint = new BGearRestraint(_nodeA, _nodeB);
	_restraint->setAxisA(0, 0, 1);
	_restraint->setAxisB(0, 0, 1);
	_restraint->setName("Hinge");
}
GearHandler::~GearHandler()
{

}

void GearHandler::attached(BViewer* viewer)
{
	BScene* scene = (BScene*)viewer->scene();
	_nodeA->setPosition(0, 0, 5);
	_nodeB->setPosition(2, 2, 5);
	scene->insert(_nodeA);
	scene->insert(_nodeB);
	scene->insert(_hingeA);
	scene->insert(_hingeB);
	scene->insert(_restraint);
	//if (BBody* bodyA = _nodeA->asset())
	//{
	//	BMatrix matrix;
	//	matrix.setPosition(BVector(0, 0, 3));
	//	bodyA->setWorldTransform(matrix);
	//}
	//if (BBody* bodyB = _nodeB->asset())
	//{
	//	BMatrix matrix;
	//	matrix.setPosition(BVector(2, 2, 3));
	//	bodyB->setWorldTransform(matrix);
	//}
	this->emit("edit-restraint", _restraint);
}
void GearHandler::detached(BViewer* viewer)
{
	BScene* scene = viewer->scene();
	scene->remove(_nodeA);
	scene->remove(_nodeB);
	scene->remove(_restraint);
}

void GearHandler::paint(BPainter& painter)
{
	BViewer* viewer = this->viewer();
}
void GearHandler::render(BRender& render)
{
	render.setLighting(false);
	render.setDepthTest(false);
	render.setLineSmooth(true);
	render.setLineWidth(1);

	BNode* nodeA = _restraint->bodyA();
	const BMatrix& matrixA = nodeA->matrix();
	BVector pointA = matrixA * _restraint->pivotA();

	BNode* nodeB = _restraint->bodyB();
	const BMatrix& matrixB = nodeB->matrix();
}

void GearHandler::styleEvent(const BEvent& event)
{
	BHandler::styleEvent(event);
	const BStyle* style = event.value();
	BImage* image = style->image("cone-texture");
	if (BShape* shape = _nodeA->shape(0))
	{
		shape->setTexture(image);
	}
	if (BShape* shape = _nodeB->shape(0))
	{
		shape->setTexture(image);
	}
}